/**
 * 公告管理模块
 * 负责管理公司公告信息，包括公告的发布、编辑、删除和状态管理等
 */

// 定义状态
const state = {
  list: [] // 公告列表
}

// 定义mutation
const mutations = {
  // 设置公告列表
  SET_LIST(state, list) {
    state.list = list
  },
  // 添加新公告
  ADD_ANNOUNCEMENT(state, announcement) {
    state.list.push(announcement)
  },
  // 编辑公告
  EDIT_ANNOUNCEMENT(state, announcement) {
    const idx = state.list.findIndex(a => a.id === announcement.id)
    if (idx !== -1) state.list.splice(idx, 1, announcement)
  },
  // 删除公告
  DELETE_ANNOUNCEMENT(state, id) {
    state.list = state.list.filter(a => a.id !== id)
  }
}

// 定义action
const actions = {
  // 获取公告列表
  fetchList({ commit, state }) {
    // 如果已有数据，直接使用
    if (state.list && state.list.length > 0) {
      console.log('announcement.js: state already populated, skipping initial fetch');
      return;
    }
    // 模拟异步获取公告列表数据
    setTimeout(() => {
      commit('SET_LIST', [
        { id: 1, title: '公司例会通知', content: '全体员工请于周五参加公司例会...', date: '2025-03-18', type: 'notice', publisher: '人事部', publishTime: '2024-03-18 10:00:00', status: 'published' },
        { id: 2, title: '办公室搬迁通知', content: '公司将于下月搬迁至新地址...', date: '2025-03-15', type: 'announcement', publisher: '行政部', publishTime: '2024-03-15 14:30:00', status: 'draft' }
      ])
    }, 500);
  },

  // 添加新公告
  addAnnouncement({ commit, state }, announcement) {
    // 生成新公告ID
    announcement.id = state.list.length ? Math.max(...state.list.map(a => a.id)) + 1 : 1;
    // 新增时补充默认字段
    const newAnnouncement = { 
      ...announcement,
      publisher: announcement.publisher || '当前用户', // 默认为当前用户
      publishTime: announcement.publishTime || new Date().toLocaleString(), // 默认为当前时间
      status: announcement.status || 'draft' // 默认为草稿状态
    };
    commit('ADD_ANNOUNCEMENT', newAnnouncement);
  },

  // 编辑公告
  editAnnouncement({ commit }, announcement) {
    commit('EDIT_ANNOUNCEMENT', announcement);
  },

  // 删除公告
  deleteAnnouncement({ commit }, id) {
    commit('DELETE_ANNOUNCEMENT', id);
  },

  // 发布公告
  publishAnnouncement({ commit, state }, id) {
    const announcement = state.list.find(a => a.id === id);
    if (announcement) {
      const updatedAnnouncement = { ...announcement, status: 'published' };
      commit('EDIT_ANNOUNCEMENT', updatedAnnouncement);
    }
  }
}

// 导出模块
export default {
  namespaced: true, // 启用命名空间
  state,
  mutations,
  actions
} 